import axios, { AxiosResponse } from 'axios'
import { ElMessage } from 'element-plus'
import router from '../router'
const server=axios.create({
  baseURL:'/shopApi',
  headers:{
    'Content-Type': 'multipart/form-data'
  },
  timeout:5000
})
// 刷新token专用
const serverRefreshToken=axios.create({
  baseURL:'/shopApi',
  timeout:5000
})
async function getNewToken(){
  let res=await serverRefreshToken.request({
    url:`/admin/refresh`,
    method:"post",
  })
  if(res.status==200){
    sessionStorage.setItem("token",res.data.token)
    sessionStorage.setItem("refreshToken",res.data.refreshToken)
    return true
  }else{
    ElMessage.error(res.data.message)
    router.push('/login')
    return false
  }
}
server.interceptors.request.use(config=>{
  let token=""
  token=sessionStorage.getItem("token") as string
  if(token){
    config.headers.Authorization="Bearer "+token
  }
  return config
},error=>{
  Promise.reject(error)
})
let isRefreshing=false
let refreshFnArr:Function[]=[]
server.interceptors.response.use(async(res)=>{
  if(res.status==201){
    if(!isRefreshing){
      isRefreshing=true
      let bl=await getNewToken()
      if(bl){
        refreshFnArr.forEach(fn=>{
          fn()
        })
        refreshFnArr=[]
        res= await server.request(res.config)
        isRefreshing=false
      }
    }else{
      return new Promise(resolve=>{
        refreshFnArr.push(
          ()=>{
            resolve(res.config as AxiosResponse)
          }
        )
      })
    }
  }
  return res
},error=>{
  if(error.response.status==500||error.response.status==401){
    router.push('/login')
    ElMessage.error(error.response.data.message)
    Promise.reject(error)
  }
  
})

serverRefreshToken.interceptors.request.use(config=>{
  let token=""
  token=sessionStorage.getItem("refreshToken") as string
  if(token){
    config.headers.Authorization="Bearer "+token
  }
  return config
},error=>{
  Promise.reject(error)
})
export default server